package com.gitee.shigen.common.handler;

import com.gitee.shigen.common.exception.BaseException;
import com.gitee.shigen.common.msg.Result;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author shigenfu
 */
@ControllerAdvice("com.gitee.shigen")
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public Result<String> baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        log.error(ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return new Result<>(ex.getStatus(), ex.getMessage(), null);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(ex.getMessage(), ex);
        return Result.failed(ex.getMessage());
    }

}
